import { login } from '@/services/ant-design-pro/api';
import {history } from 'umi';
import {Toast, Image, Tabs, Grid, Form, Button, Input} from 'antd-mobile';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import React, {useState} from 'react';
import {useModel} from "@umijs/max";
import {Divider} from "antd";
import {
  AppleFilled,
  LockOutlined,
  QqOutlined,
  UserOutlined,
  WechatOutlined
} from "@ant-design/icons";
import {useEmotionCss} from "@ant-design/use-emotion-css";

// 判断请求头
const isAndroid = navigator.userAgent.indexOf("Android")
const isIos = navigator.userAgent.indexOf("iPhone")
let fromMobile = false
if(isAndroid > -1 || isIos > -1){
  fromMobile = true
}
if (!fromMobile){
  // 电脑请求，转向电脑版
  window.location.href="https://x.sgdev.cn/"
  // window.location.href="https://81.71.2.115/"
}

const Login: React.FC = () => {
  // 密码可见
  const [visible, setVisible] = useState(false)
  const { initialState, setInitialState } = useModel('@@initialState');

  // 获取用户数据，菜单数据
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      const menus = await initialState?.fetchUserMenus?.();
      await setInitialState({
        ...initialState,
        currentUser: userInfo,
        menuData: menus,
      });
    }
  };

  // 账户密码登录验证
  const handleLoginSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = await login({ ...values});
      if (msg) {
        if (msg.access) {
          // 成功获取到token
          // 保存token
          localStorage.setItem('token', msg.access);
          localStorage.setItem('is_first_login', msg.is_first_login);

          await fetchUserInfo();
          history.push('/m/addLogs');
          return;
        } else {

          // 没有获取到token，用户名/密码错误
          Toast.show({
            content: msg.message,
            icon: "fail"
          });
        }
      }else {
        Toast.show({
          content: "Token获取失败，请重试！" + msg,
          icon: "fail"
        });
      }
      // 如果失败去设置用户错误信息
    } catch (error) {
      console.log(error)
      Toast.show({
        content: "登录失败，请重试！" + error,
        icon: "fail"
      });
    }
  };

  // 扫码登录方式
  function OauthLogin(t: string) {
    let info: string;
    if (t === 'apple') {

      info = '苹果登录未开放！'
    } else if (t === 'wechat') {

      info = '微信登录未开放！'
    } else {

      // 使用public下的dingtalk.html构造钉钉二维码扫码登录
      // window.location.href="/dingtalk.html"
      // return
      info = 'QQ登录未开放！'
    }
    return (
      Toast.show({
        content: info,
        icon: "fail"
      })
    )
  }
  const loginBodyStyle = useEmotionCss(()=> {
    return {
      height: "100%",
      overflow: "hidden",
      backgroundImage: 'url("https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg") !important',
      backgroundRepeat: "no-repeat",
      backgroundSize: "100%",
      backgroundPosition: "center 110px",
      position: "relative",
      background: "#f0f2f5",
    }
  })
  const loginHeaderStyle = useEmotionCss(()=> {
    return {
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      height: "44px",
      lineHeight: "44px",
      marginTop: "50px",
    }
  })
  const loginLogoStyle = useEmotionCss(()=> {
    return {
      marginTop: "5px",
      marginRight: "5px",
    }
  })
  const loginTitleStyle = useEmotionCss(()=> {
    return {
      position: 'relative',
      insetBlockStart: "2px",
      fontWeight: '600',
      fontSize: '28px',
      textAlign: 'center',
      backgroundImage: 'linear-gradient(to right, blue, purple)',
      backgroundClip: 'text',
      color: "transparent"
    }
  })
  const socialIconStyle = useEmotionCss(()=>{
    return {
      fontSize: '24px',
      color: '#8c8c8c',
      paddingRight: '8px',
      hover: {
        color: 'red',
      }
    }
  })
  const eyeStyle = useEmotionCss(()=>{
    return {
      padding: '4px',
      cursor: 'pointer',
      svg: {
        display: 'block',
        fontSize: '30px',
      }
    }
  })
  const extraPartStyle = useEmotionCss(()=>{
    return {
      fontSize: '24px',
      color: '#8c8c8c',
      paddingRight: '8px',
    }
  })
  return (
    <div className={loginBodyStyle}>
      <div className={loginHeaderStyle}>
        <div className={loginLogoStyle}>
          <Image
            src={"/logo.svg"}
            style={{width: 50, height: 50}}
          />
        </div>
        <div className={loginTitleStyle}>
          极简流水账
        </div>
      </div>
      <div style={{marginTop: 100}}>
        <Tabs defaultActiveKey={"byPassword"}>
          <Tabs.Tab title={"密码登录"} key={"byPassword"}>
            <Form
              layout='horizontal'
              mode='card'
              footer={
                <Button style={{borderRadius: 8}} block type='submit' color='primary' size='large'>
                  登录
                </Button>
              }
              onFinish={(value)=>{
                if (value.account === "" || value.account === undefined){
                  Toast.show({
                    content: "请输入账号/手机号/邮箱！",
                    icon: "fail"
                  })
                }else if (value.password === "" || value.password === undefined){
                  Toast.show({
                    content: "请输入密码！",
                    icon: "fail"
                  })
                }else {

                  // 输入完整，开始验证
                 handleLoginSubmit(value).then(r => console.log(r));
                }
              }
              }
            >
              <Form.Header/>
              <Form.Item
                name={"account"}
                label={<UserOutlined/>}
                style={{
                  "--prefix-width": "38px"
                }}
              >
                <Input style={{lineHeight: 38, height: 38}} placeholder={"账号/手机号/邮箱"}/>
              </Form.Item>
              <Form.Header/>
              <Form.Item
                name={"password"}
                style={{
                  "--prefix-width": "38px"
                }}
                label={<LockOutlined/>}
                extra={
                  <div className={eyeStyle}>
                    {!visible ? (
                      <EyeInvisibleOutline onClick={() => setVisible(true)} />
                    ) : (
                      <EyeOutline onClick={() => setVisible(false)} />
                    )}
                  </div>
                }
              >
                <Input style={{lineHeight: 38, height: 38}}  type={visible ? 'text' : 'password'} clearable placeholder={"密码"}/>
              </Form.Item>
            </Form>
          </Tabs.Tab>
          <Tabs.Tab title={"验证码登录"} key={"byCode"}>
            <Form
              layout='horizontal'
              mode='card'
              footer={
                <Button style={{borderRadius: 8}} block type='submit' color='primary' size='large'>
                  登录
                </Button>
              }
              onFinish={(value)=>{
                console.log(value)
                if (value.account === "" || value.account === undefined){
                  Toast.show({
                    content: "请输入手机号或者邮箱！",
                    icon: "fail"
                  })
                }else if (value.code === "" || value.code === undefined){
                  Toast.show({
                    content: "请输入验证码！",
                    icon: "fail"
                  })
                }else {
                  // 输入完整，开始验证
                  Toast.show({
                    content: "验证码登录功能未开放！",
                    icon: "fail"
                  })
                }
              }
            }
            >
              <Form.Header/>
              <Form.Item
                style={{
                  "--prefix-width": "38px"
                }}
                name={"account"}
                label={<UserOutlined/>}
              >
                <Input style={{lineHeight: 38, height: 38}}  placeholder={"手机号/邮箱"}/>
              </Form.Item>
              <Form.Header/>
              <Form.Item
                style={{
                  "--prefix-width": "38px"
                }}
                label={<LockOutlined/>}
                name={"code"}
                extra={
                  <div className={extraPartStyle}>
                    <a onClick={()=>{
                      Toast.show({
                        content: "验证码登录功能未开放！",
                        icon: "fail"
                      })
                    }}>发送验证码</a>
                  </div>
                }
              >
                <Input style={{lineHeight: 38, height: 38}}  maxLength={6} placeholder='请输入验证码' clearable />
              </Form.Item>
            </Form>
          </Tabs.Tab>
        </Tabs>
      </div>
      <div style={{position: "absolute", bottom: 50, width: `100%`}}>
        <Divider style={{color: "#1677ff", fontSize: 15}}>社交登录</Divider>
        <Grid columns={3} gap={8}>
          <Grid.Item/>
          <Grid.Item style={{alignItems: "center", textAlign: "center"}}>
            <AppleFilled className={socialIconStyle} onClick={()=>{OauthLogin("apple")}}/>
            <WechatOutlined className={socialIconStyle} onClick={()=>{OauthLogin("wechat")}}/>
            <QqOutlined className={socialIconStyle} onClick={()=>{OauthLogin("QQ")}}/>
          </Grid.Item>
          <Grid.Item/>
        </Grid>
      </div>
    </div>
  );
};

export default Login;
